<?
if(!defined("B_PROLOG_INCLUDED")||B_PROLOG_INCLUDED!==true)die();

$arParams["USE_CAPTCHA"] = (($arParams["USE_CAPTCHA"] != "N" && !$USER->IsAuthorized()) ? "Y" : "N");
$arParams["EVENT_NAME"] = trim($arParams["EVENT_NAME"]);
if(strlen($arParams["EVENT_NAME"]) <= 0)
	$arParams["EVENT_NAME"] = "FEEDBACK_FORM";
$arParams["EMAIL_TO"] = trim($arParams["EMAIL_TO"]);
if(strlen($arParams["EMAIL_TO"]) <= 0)
	$arParams["EMAIL_TO"] = COption::GetOptionString("main", "email_from");
$arParams["OK_TEXT"] = trim($arParams["OK_TEXT"]);
if(strlen($arParams["OK_TEXT"]) <= 0)
	$arParams["OK_TEXT"] = GetMessage("MF_OK_MESSAGE");

/* проверка входных параметров для инфоблока и почты */
$arParams["ADD_INTO_IBLOCK"] = ($arParams["ADD_INTO_IBLOCK"] != "N") ? true : false ;
$arParams["ACTIVE_DEFAULT"] = ($arParams["ACTIVE_DEFAULT"] != "Y") ? "N" : "Y" ;
$arParams["SEND_EMAIL"] = ($arParams["SEND_EMAIL"] != "N") ? true : false ;


if($_SERVER["REQUEST_METHOD"] == "POST" && strlen($_POST["submit"]) > 0)
{
	if(check_bitrix_sessid())
	{
		/* Проверка заполненности обязательных полей на основе того, какому типу соответствует поле */
		if (!empty($arParams["REQUIRED_FIELDS"]))
		{
			foreach($arParams["REQUIRED_FIELDS"] as $field):
				if (array_key_exists($field, $arParams["FORM_FIELDS"])):
					switch ($arParams["FORM_FIELDS"][$field]["TYPE"])
					{
						case "STRING" :
							if (strlen($_POST[$field]) <= 1)
								$arResult["ERROR_MESSAGE"][] = str_replace("#FIELD#", $arParams["FORM_FIELDS"][$field]["TITLE"], GetMessage("MF_FIELD_EMPTY"));
							break;
						case "EMAIL" :
							if (strlen($_POST[$field]) <= 1)
								$arResult["ERROR_MESSAGE"][] = str_replace("#FIELD#", $arParams["FORM_FIELDS"][$field]["TITLE"], GetMessage("MF_FIELD_EMPTY"));
							elseif (!check_email($_POST[$field]))
								$arResult["ERROR_MESSAGE"][] = GetMessage("MF_EMAIL_NOT_VALID");
							break;
						case "TEXT" :
							if (strlen($_POST[$field]) <= 3)
								$arResult["ERROR_MESSAGE"][] = str_replace("#FIELD#", $arParams["FORM_FIELDS"][$field]["TITLE"], GetMessage("MF_FIELD_EMPTY"));
							break;
					};
				else:
					$arResult["ERROR_MESSAGE"][] = str_replace("#FIELD#", $field, GetMessage("MF_FIELD_NO_FORM"));
				endif;
			endforeach;
		}
		if($arParams["USE_CAPTCHA"] == "Y")
		{
			include_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/classes/general/captcha.php");
			$captcha_code = $_POST["captcha_sid"];
			$captcha_word = $_POST["captcha_word"];
			$cpt = new CCaptcha();
			$captchaPass = COption::GetOptionString("main", "captcha_password", "");
			if (strlen($captcha_word) > 0 && strlen($captcha_code) > 0)
			{
				if (!$cpt->CheckCodeCrypt($captcha_word, $captcha_code, $captchaPass))
					$arResult["ERROR_MESSAGE"][] = GetMessage("MF_CAPTCHA_WRONG");
			}
			else
				$arResult["ERROR_MESSAGE"][] = GetMessage("MF_CAPTHCA_EMPTY");

		}	
		if(empty($arResult))
		{
			/* insert2iblock
				Вставка элемента в Инфоблок, если он задан */
			if ($arParams["ADD_INTO_IBLOCK"])
			{
				if(CModule::IncludeModule("iblock"))
				{
					$arIBlockInsert = Array(
						"IBLOCK_ID" => $arParams["IBLOCK_ID"],
						"ACTIVE" => $arParams["ACTIVE_DEFAULT"]
					);
					// смотрим, какие поля вообще необходимо заполнять
					// выделяем отдельно свойства инфоблока
					foreach($arParams["IBLOCK_TO_FORM"] as $iblock_field => $form_field)
					{
						// если это текущая дата, то заносим ее сразу, без дальнейших операций
						if ($form_field == "#DATE_NOW#")
						{
							if (strpos($iblock_field, "PROPERTY_") === false)
							{
								$arIBlockInsert[$iblock_field] = ConvertTimeStamp();
							}
							else
							{
								$propName = substr($iblock_field, 9);
								$arIBlockInsertProps[$propName] = ConvertTimeStamp();
							}
						}
						else
						{
							if (strpos($iblock_field, "PROPERTY_") === false)
							{
								$arIBlockInsert[$iblock_field] = $_POST[$form_field];
							}
							else
							{
								$propName = substr($iblock_field, 9);
								if ($arParams["FORM_FIELDS"][$form_field]["TYPE"] == "TEXT")
								{
									$arIBlockInsertProps[$propName] = Array("VALUE" => array("TYPE" => "text", "TEXT" => htmlspecialchars($_POST[$form_field])));
								}
								else
								{
									$arIBlockInsertProps[$propName] = $_POST[$form_field];
								}
							};
						};
					};
					$arIBlockInsert["PROPERTY_VALUES"] = $arIBlockInsertProps;
					// если указаны обязательные поля
					if (!empty($arIBlockInsert["NAME"]))
					{
						// то добавляем элемент в инфоблок
						$el = new CIBlockElement;
						#echo "<pre>"; print_r($arIBlockInsert); echo "</pre>"; die();
						if (!($ITEM_ID = $el->Add($arIBlockInsert)))
							$arResult["ERROR_MESSAGE"][] = $el->LAST_ERROR;
					}
					else
					{
						// иначе ошибка
						$arResult["ERROR_MESSAGE"][] = GetMessage("MF_IBLOCK_NAME_EMPTY");
					}
				}
				else
				{
					$arResult["ERROR_MESSAGE"][] = GetMessage("MF_IBLOCK_INCLUDE_ERROR");
				}
			}
			/* /insert2iblock */
			
			/* create email message */
			
			if ($arParams["SEND_EMAIL"])
			{
				$arEmailFields = Array();
				$arEmailFields["EMAIL_TO"] = $arParams["EMAIL_TO"];
				foreach($arParams["MAIL_TO_FORM"] as $mail_field=>$form_field)
				{
					if ($form_field == "#DATE_NOW#")
					{
						$arEmailFields[$mail_field] = ConvertTimeStamp();
					}
					else
					{
						$arEmailFields[$mail_field] = $_POST[$form_field];
					}
				};
				#echo "<pre>"; print_r($arEmailFields); echo "</pre>"; die();
				if (!($event_id = CEvent::Send($arParams["EVENT_NAME"], SITE_ID, $arEmailFields)))
					$arResult["ERROR_MESSAGE"][] = GetMessage("MF_ERROR_SEND_EMAIL");
			}
			
			/* /create email message */
			
			// сохраняем в переменных сессии значения введенных данных, чтобы можно было их восстановить после редиректа
			foreach($arParams["FORM_FIELDS"] as $form_field=>$arField)
			{
				$_SESSION["MF_".$form_field] = htmlspecialcharsEx($_POST[$form_field]);
			}
			LocalRedirect($APPLICATION->GetCurPageParam("success=Y", Array("success")));
		}

		// если есть ошибки, сохраняем в результате выдачи предыдущие введенные данные
		foreach($arParams["FORM_FIELDS"] as $form_field=>$arField)
		{
			$arResult[$form_field] = htmlspecialcharsEx($_POST[$form_field]);
		}
	}
	else
		$arResult["ERROR_MESSAGE"][] = GetMessage("MF_SESS_EXP");
}
elseif($_REQUEST["success"] == "Y")
{
	$arResult["OK_MESSAGE"] = $arParams["OK_TEXT"];
}

if(empty($arResult["ERROR_MESSAGE"]))
{
	foreach ($arParams["FORM_FIELDS"] as $form_field=>$arField)
	{
		if(strlen($_SESSION["MF_".$form_field]) > 0)
			$arResult[$form_field] = htmlspecialcharsEx($_SESSION["MF_".$form_field]);
	}
}

if($arParams["USE_CAPTCHA"] == "Y")
	$arResult["capCode"] =  htmlspecialchars($APPLICATION->CaptchaGetCode());

$this->IncludeComponentTemplate();
?>